﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using Common;

namespace Ex03
{
    /// <summary>
    /// Reformulating the subquery
    /// </summary>
    class Program
    {
        static void Main(string[] args)
        {
            // For more information on subqueries, see Chapter 9, "Projecting"
            var list = new List<string>();
            for (int i = 0; i < 100000; i++)
            {
                list.Add(i.ToString());
            }

            string[] names = list.ToArray();

            //names.Where(n => n.Length ==
            //names.OrderBy(n2 => n2.Length).Select(n2 => n2.Length).First()
            //)
            //     .Dump();
            var stopwatch = new Stopwatch();
            stopwatch.Start();
            var query =
                from n in names
                where n.Length == (from n2 in names orderby n2.Length select n2.Length).First()
                select n;
            query.ToList();
            //query.Dump("Same thing as a query expression");
            stopwatch.Stop();
            Console.WriteLine(stopwatch.ElapsedMilliseconds);
            query =
                from n in names
                where n.Length == names.OrderBy(n2 => n2.Length).First().Length
                select n;

            query.Dump("Reformulated");

            query =
                from n in names
                where n.Length == names.Min(n2 => n2.Length)
                select n;

            query.Dump("Same result, using Min aggregation");
            Console.ReadKey();
        }
    }
}
